/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SQL.java
 *
 * Created on Aug 9, 2011, 5:42:58 PM
 */
package azure;

import java.sql.*;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.jdesktop.application.Action;

/**
 *
 * @author Gargravarr
 */
public class JQL extends javax.swing.JFrame
{

    Connection sqlConn;

    /** Creates new form SQL */
    public JQL()
    {
	initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtResults = new javax.swing.JTextArea();
        jtFile = new javax.swing.JTextField();
        jbConnect = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jlFile = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtQuery = new javax.swing.JTextArea();
        jbQuery = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jbBrowse = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jtResults.setColumns(20);
        jtResults.setEditable(false);
        jtResults.setLineWrap(true);
        jtResults.setRows(5);
        jtResults.setName("jtResults"); // NOI18N
        jScrollPane1.setViewportView(jtResults);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(azure.Main.class).getContext().getResourceMap(JQL.class);
        jtFile.setText(resourceMap.getString("jtFilename.text")); // NOI18N
        jtFile.setName("jtFilename"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(azure.Main.class).getContext().getActionMap(JQL.class, this);
        jbConnect.setAction(actionMap.get("connect")); // NOI18N
        jbConnect.setText(resourceMap.getString("jbConnect.text")); // NOI18N
        jbConnect.setName("jbConnect"); // NOI18N

        jSeparator1.setName("jSeparator1"); // NOI18N

        jlFile.setText(resourceMap.getString("jlDatabaseFile.text")); // NOI18N
        jlFile.setName("jlDatabaseFile"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jtQuery.setColumns(20);
        jtQuery.setRows(5);
        jtQuery.setName("jtQuery"); // NOI18N
        jScrollPane2.setViewportView(jtQuery);

        jbQuery.setAction(actionMap.get("performQuery")); // NOI18N
        jbQuery.setText(resourceMap.getString(" jbQuery.text")); // NOI18N
        jbQuery.setEnabled(false);
        jbQuery.setName(" jbQuery"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jbBrowse.setAction(actionMap.get("browseForDBFile")); // NOI18N
        jbBrowse.setText(resourceMap.getString("jbBrowse.text")); // NOI18N
        jbBrowse.setName("jbBrowse"); // NOI18N

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 430, Short.MAX_VALUE)
            .add(jPanel1Layout.createSequentialGroup()
                .add(6, 6, 6)
                .add(jlFile)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jtFile, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE)
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jbConnect)
                    .add(jbBrowse))
                .add(44, 44, 44))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 340, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jbQuery))
            .add(jPanel1Layout.createSequentialGroup()
                .add(9, 9, 9)
                .add(jLabel2)
                .addContainerGap(377, Short.MAX_VALUE))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 430, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1Layout.createSequentialGroup()
                        .add(25, 25, 25)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jlFile)
                            .add(jtFile, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .add(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jbBrowse)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(jbConnect)))
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jbQuery)
                    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(8, 8, 8)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel2)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 102, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[])
    {
	/* Set the Nimbus look and feel */
	//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
	 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
	 */
	try
	{
	    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
	    {
		if ("Nimbus".equals(info.getName()))
		{
		    javax.swing.UIManager.setLookAndFeel(info.getClassName());
		    break;
		}
	    }
	}
	catch (ClassNotFoundException ex)
	{
	    java.util.logging.Logger.getLogger(JQL.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	}
	catch (InstantiationException ex)
	{
	    java.util.logging.Logger.getLogger(JQL.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	}
	catch (IllegalAccessException ex)
	{
	    java.util.logging.Logger.getLogger(JQL.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	}
	catch (javax.swing.UnsupportedLookAndFeelException ex)
	{
	    java.util.logging.Logger.getLogger(JQL.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	}
	//</editor-fold>

	/* Create and display the form */
	java.awt.EventQueue.invokeLater(new Runnable()
	{

	    public void run()
	    {
		new JQL().setVisible(true);
	    }
	});
    }

    @Action
    public void connect()
    {
	try
	{
	    if (jtFile.isEnabled())
	    {
		Class.forName("org.sqlite.JDBC");
		sqlConn = DriverManager.getConnection("jdbc:sqlite:" + jtFile.getText());
		jtFile.setEnabled(false);
		jbConnect.setText("Disconnect");
		jbQuery.setEnabled(true);

	    }
	    else
	    {
		sqlConn.close();
		jtFile.setEnabled(true);
		jbConnect.setText("Connect");
		jbQuery.setEnabled(false);
	    }
	}
	catch (SQLException se)
	{
	    JOptionPane.showMessageDialog(rootPane, "Database does not exist!");
	}
	catch (ClassNotFoundException cnf)
	{
	    JOptionPane.showMessageDialog(rootPane, "Class not found");
	}
    }

    @Action
    public void browseForDBFile()
    {
	JFileChooser dbChooser = new JFileChooser(new java.io.File("").getAbsolutePath());
	if (dbChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
	{
	    jtFile.setText(dbChooser.getSelectedFile().toString());
	}
    }

    @Action
    public void performQuery()
    {
	if (sqlConn != null)
	{
	    String sqlString = jtQuery.getText();
	    try
	    {
		Statement sqlStatement = sqlConn.createStatement();
		if (sqlStatement.execute(sqlString) == true)
		{
		    ResultSet queryResults;
		    if ((queryResults = sqlStatement.getResultSet()) != null)
		    {
			StringBuilder sb = new StringBuilder();
			sb.append(sqlString).append("\n");
			ResultSetMetaData tableMeta = queryResults.getMetaData();
			for (int i = 1; i <= tableMeta.getColumnCount(); i += 1)
			{
			    sb.append(tableMeta.getColumnName(i));
			    sb.append("-");
			}
			sb.append("\n");
			while (queryResults.next())
			{
			    for (int i = 1; i <= tableMeta.getColumnCount(); i++)
			    {
				sb.append(queryResults.getString(i).toString());
				sb.append("-");
			    }
			    sb.append("\n");
			}
			jtResults.setText(sb.toString());
		    }
		}
		    else
		{
		    jtResults.setText(sqlStatement.getUpdateCount() + " rows affected");
		}
		sqlStatement.close();
	    }
	    
	    catch (SQLException se)
	    {
		jtResults.setText("SQL Query failed: " + se.getLocalizedMessage());
	    }
	}
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JButton jbBrowse;
    private javax.swing.JButton jbConnect;
    private javax.swing.JButton jbQuery;
    private javax.swing.JLabel jlFile;
    private javax.swing.JTextField jtFile;
    private javax.swing.JTextArea jtQuery;
    private javax.swing.JTextArea jtResults;
    // End of variables declaration//GEN-END:variables
}
